<template>
  <div>
    <h3>
      一次性渲染多条数据(伪解决方案类似分页,使用 setTimeout
      还是解决不了卡顿问题,没有好的办法建议'优化后端'):
    </h3>
    <el-checkbox
      :indeterminate="isIndeterminate"
      v-model="checkAll"
      @change="handleCheckAllChange"
      >全选</el-checkbox
    >
    <div style="margin: 15px 0"></div>
    <el-checkbox-group
      v-model="checkedCities"
      @change="handleCheckedCitiesChange"
    >
      <el-checkbox v-for="city in cities" :label="city.id" :key="city.id">{{
        city.name
      }}</el-checkbox>
    </el-checkbox-group>
  </div>
</template>
<script>
import { getList } from "@/apis/list";

export default {
  data() {
    return {
      checkAll: false, // 全选
      checkedCities: [], // 默认勾选
      cities: [], // checkbox 数据
      isIndeterminate: false, // 控制全选按钮样式
    };
  },
  created() {
    // for (let index = 0; index < 800; index++) {
    //   this.cities.push(index);
    // }
    // this.loadAll(this.cities);
    this.onLoad();
  },
  methods: {
    onLoad() {
      getList().then((res) => {
        console.log(res.data);
        // this.cities = res.data.list;
        this.loadAll(res.data.list);
      });
    },
    loadAll(response, num = 500) {
      const taht = this;

      //数据分组函数（每组 num 条）
      const group = (data) => {
        var result = [];
        var groupItem;
        for (var i = 0; i < data.length; i++) {
          if (i % num == 0) {
            groupItem != null && result.push(groupItem);
            groupItem = [];
          }
          groupItem.push(data[i]);
        }
        result.push(groupItem);
        return result;
      };
      var currIndex = 0;
      //加载某一批数据的函数
      const loadPart = (group, index) => {
        var data = [];
        for (var i = 0; i < group.length; i++) {
          data.push(group[i]);
        }
        //保证顺序不错乱
        while (index - currIndex == 1) {
          // taht.checkedCities = [...taht.checkedCities, ...data];
          taht.cities = taht.cities.concat(data);
          currIndex = index;
        }
      };

      //将1万条数据分组， 每组500条，一共20组
      var groups = group(response);
      for (var i = 0; i < groups.length; i++) {
        //闭包， 保持i值的正确性
        window.setTimeout(
          (function () {
            var group = groups[i];
            var index = i + 1;
            return function () {
              //分批渲染
              loadPart(group, index);
            };
          })(),
          1
        );
      }
    },

    handleCheckAllChange(val) {
      // if (val) {
      //   this.loadAll(this.cities);
      // } else {
      //   this.checkedCities = [];
      // }
      this.checkedCities = val ? this.cities : [];
      this.isIndeterminate = false;
    },
    handleCheckedCitiesChange(value) {
      let checkedCount = value.length;
      this.checkAll = checkedCount === this.cities.length;
      this.isIndeterminate =
        checkedCount > 0 && checkedCount < this.cities.length;
    },
  },
};
</script>